package com.streamhub.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.visualizations.Table;
import com.google.gwt.visualization.client.visualizations.Table.Options;
import com.google.gwt.visualization.client.visualizations.Table.Options.Policy;

public class StockVisualizationDemo implements EntryPoint {
	private final VerticalPanel mainPanel = new VerticalPanel();
	private final String[] stocks = new String[] { "BA", "BAC", "C", "KO", "MCD", "WMT" };
	private DataTable dataTable;
	private Table dataTableWrapper;
	private StreamHubGWTAdapter streamhub;

	public void onModuleLoad() {
		dataTable = createDataTable();
		dataTableWrapper = createDataTableWrapper(dataTable);
		mainPanel.add(dataTableWrapper);
		mainPanel.addStyleName("mainPanel");
		RootPanel.get("stockTable").add(mainPanel);
		streamhub = new StreamHubGWTAdapter();
		streamhub.connect("${server.url}");
		addStocks();
	}

	private DataTable createDataTable() {
		DataTable dataTable = DataTable.create();
		dataTable.addColumn(ColumnType.STRING, "Symbol");
		dataTable.addColumn(ColumnType.STRING, "Company");
		dataTable.addColumn(ColumnType.NUMBER, "Last Price");
		dataTable.addColumn(ColumnType.NUMBER, "Change");
		dataTable.addColumn(ColumnType.NUMBER, "% Change");
		return dataTable;
	}
	
	private Table createDataTableWrapper(DataTable dataTable) {
		Table dataTableWrapper = new Table();
		Options options = Options.create();
		options.setSort(Policy.DISABLE);
		options.setOption("allowHtml", true);
		dataTableWrapper.draw(dataTable, options);
		return dataTableWrapper;
	}

	private void addStocks() {
		for (String symbol : stocks) {
			Stock stock = new Stock(symbol);
			stock.addToDataTable(dataTable, dataTableWrapper);
			streamhub.subscribe(symbol, stock);
		}
	}
}
